from selenium import webdriver
import time
import requests
from lxml import etree
from kaisha import *

# 获取二进制资源文件(图片，mp3, 视频)
def get_resource(url):
    headers =  {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        # response.content返回的是字节流，decode后变成字符串
        return response.content
    return None

def get_page():
    # 打开一个Chrome浏览器
    browser = webdriver.Chrome()
    url = 'https://emumo.xiami.com/chart'
    browser.get(url)
    # 等待网页页面元素加载完成
    time.sleep(3)
    # 获取浏览器渲染后的页面
    html = browser.page_source
    return html

# 保存mp3文件
def save_mp3(mp3_url, title):
    # 获取mp3二机制流
    mp3_content = get_resource(mp3_url)
    with open('./mp3/%s.mp3' % title, 'wb') as f:
        f.write(mp3_content)

def parse_page(html):
    etree_html = etree.HTML(html)
    result = etree_html.xpath('//tr[@class="songwrapper"]')
    for item in result:
        data_mp3 = item.xpath('./@data-mp3')[0]
        data_title = item.xpath('./@data-title')[0]
        # print(data_mp3)
        print(data_title)
        mp3_url = str2url(data_mp3)
        print(mp3_url)
        save_mp3(mp3_url, data_title)

def main():
    html = get_page()
    # print(html)
    parse_page(html)





if __name__ == '__main__':
    main()